<template>
  <a-card class="container">
    <div class="search">
      <!-- <div class="mod">
        <a-radio-group v-model="mod" button-style="solid" @change="setOptionChart">
          <a-radio-button value="campaign">
            新增计划
          </a-radio-button>
          <a-radio-button value="video">
            新增视频
          </a-radio-button>
        </a-radio-group>
      </div> -->
      <div class="time">
        <!-- <div class="salesExtra">
          <a href="javaScript:;" :class="type == item.type?'currentDate':''" v-for="(item,index) in dateType" :key="index" @click="changeType(item.type)">{{ item.name }}</a>
        </div> -->
        <a-select class="yhs" v-model="admin_userid" @change="getData">
          <a-select-option :value="0">
            全部优化师
          </a-select-option>
          <a-select-option :value="item.id" v-for="(item,index) in youhuashi" :key="index">
            {{item.username}}
          </a-select-option>
        </a-select>
        <a-select class="select" show-search :filter-option="filterOption" v-model="product_name"  @change="getData">
          <a-select-option :value="0">全部产品</a-select-option>
          <a-select-option :value="item.value" v-for="(item,index) in productList2" :key="index">{{item.label}}</a-select-option>
        </a-select>
        <!-- <a-select class="select2" mode="multiple" :maxTagCount="1" show-search :filter-option="filterOption" v-model="ziduan"  @change="setOptionChart">
          <a-select-option :value="item.value" v-for="(item,index) in ziduanOptions" :key="index">{{item.label}}</a-select-option>
        </a-select> -->
        <a-range-picker 
          :ranges="{ '当日': [moment(), moment()], 
          '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], 
          '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
          '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')],
          '本月': [moment(moment().month(moment().month()).startOf('month').valueOf()),moment()],
          '本季度':[moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()), moment()] }"
          v-model="customDateValue" @change="customDate" :disabled-date="disabledDate" />
      </div>
    </div>
    <a-card title="图表数据" class="chart">
      <div id="chart-account" style="height:500px"></div>
    </a-card>
    <CustomTable 
        class="customTable"
        rowKey="account"
        title="账户数据" 
        :dataSource="accountData" 
        :columns="columns" 
        :loading="loading"
        :downloadTitle="downloadTitle"
        :scroll="{x:1200}"
        :pagination="{showTotal:total => `共 ${total} 条数据`, pageSize: pageSize,showLessItems: true, showSizeChanger:true,pageSizeOptions:['10', '20', '50', '100']}"
      >
      <div slot="account" slot-scope="{record}" >
        <a-tooltip>
          <template slot="title">
            {{record.account}}
          </template>
          <span style="display: block;cursor: pointer;;white-space: nowrap;">{{record.account}}</span>
        </a-tooltip>
      </div>
      <div slot="ctr" slot-scope="{record}">
        {{(record.ctr*100).toFixed(2) + '%'}}
      </div>
      <div slot="cvr" slot-scope="{record}">
        {{(record.cvr*100).toFixed(2) + '%'}}
      </div>
    </CustomTable>
  </a-card>
</template>

<script>
import CustomTable from '@/components/table/CustomTable'
import moment from 'moment';
import { getOptimizerList } from '@/api/xinxiliu/account'
import { getAccountCampaignAndVideoNumDays,getAccountCampaignAndVideoNum, getOptionSelectProduct } from '@/api/dianshang/dianshang'
import { init, setOption3 } from './createChart'

export default {
  data() {
    return {
      moment,
      mod: 'campaign',
      type: 0,
      admin_userid:0,
      dateType: [
        {name:'当日', type:1},
        {name:'昨日', type:2},
        {name:'过去一周', type:3},
        {name:'过去30天', type:4},
        {name:'本月', type:5},
        {name:'本季度', type:6},
      ],
      ziduan:['计划数量', '视频数量', '广告消耗', '点击率', '转化率', 'GMV', 'ROI'],
      ziduanOptions: [
        { label: '计划数量', value: 'campaign_num' },
        { label: '视频数量', value: 'video_num' },
        { label: '广告消耗', value: 'cost' },
        { label: '点击率', value: 'ctr' },
        { label: '转化率', value: 'cvr' },
        { label: 'GMV', value: 'gmv' },
        { label: 'ROI', value: 'roi' },
      ],
      customDateValue: [moment().add(-7, 'days'), moment().add(-1, 'days')],
      youhuashi: [],
      chartData: [],
      accountData: [],
      loading: false,
      downloadTitle: '账户日报',
      pageSize: 10,
      product_name: 0,
      productList2: [],
      columns: [
        {
          title: '账户',
          width: 150,
          dataIndex: 'account',
          scopedSlots: {
            customRender: 'account'
          },
          filtered: true
        },
        {
          title: '优化师',
          width: 100,
          dataIndex: 'username',
        },
        {
          title: '计划数量',
          width: 130,
          dataIndex: 'campaign_num',
          sorter: (a, b) => a.campaign_num - b.campaign_num,
        },
        {
          title: '视频数量',
          width: 130,
          dataIndex: 'video_num',
          sorter: (a, b) => a.video_num - b.video_num,
        },
        {
          title: '广告消耗',
          width: 130,
          dataIndex: 'cost',
          sorter: (a, b) => a.cost - b.cost,
        },
        {
          title: '点击率',
          width: 130,
          dataIndex: 'ctr',
          scopedSlots: {
            customRender: 'ctr'
          },
          sorter: (a, b) => a.ctr - b.ctr,
        },
        {
          title: '转化率',
          width: 130,
          dataIndex: 'cvr',
          scopedSlots: {
            customRender: 'cvr'
          },
          sorter: (a, b) => a.cvr - b.cvr,
        },
        {
          title: 'GMV',
          width: 130,
          dataIndex: 'gmv',
          sorter: (a, b) => a.gmv - b.gmv,
        },
        {
          title: 'ROI',
          width: 130,
          dataIndex: 'roi',
          sorter: (a, b) => a.roi - b.roi,
        },
      ],
      timeout:null
    }
  },
  created() {
    this.getData()
    this.getOptimizerList()
    this.getProductList()
  },
  mounted() {
  },
  activated() {
    this.initChart()
    this.$EventBus.$on('onresize', this.initChart)
  },
  methods: {
    getData() {
      this.getChartData()
      this.getAccountData()
    },
    getChartData() {
      const params = {
        type: 7,
        start_date: moment(this.customDateValue[0]).format('YYYY-MM-DD'),
        end_date: moment(this.customDateValue[1]).format('YYYY-MM-DD'),
      }
      if (this.product_name != 0) {
        params['product_name'] = this.product_name
      }
      if (this.admin_userid != 0) {
        params['admin_userid'] = this.admin_userid
      }
      getAccountCampaignAndVideoNumDays(params).then((res) => {
        if (res.errcode == 0) {
          this.chartData = res.data
          this.setOptionChart()
        }
      }).catch(() => {
        
      });
    },
    getAccountData() {
      const params = {
        type: 7,
        start_date: moment(this.customDateValue[0]).format('YYYY-MM-DD'),
        end_date: moment(this.customDateValue[1]).format('YYYY-MM-DD'),
      }
      this.loading = true
      if (this.product_name != 0) {
        params['product_name'] = this.product_name
      }
      if (this.admin_userid != 0) {
        params['admin_userid'] = this.admin_userid
      }
      getAccountCampaignAndVideoNum(params).then((res) => {
        this.loading = false
        if (res.errcode == 0) {
          this.accountData = res.data
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getProductList(){
      let params = {
        page: 1,
        pagesize: 99999,
      }
      getOptionSelectProduct(params).then((res) => {
        if(res.errcode == 0){
          this.productList2 = res.data
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getOptimizerList(){
      // 获取优化师列表
      getOptimizerList({}).then((res) => {
        if(res.errcode == 0){
          this.youhuashi = res.data
        }
      });
    },
    customDate(date) {
      this.customDateValue = date
      this.type = 0
      this.getData()
    },
    changeType(type) {
      this.type = type
      this.customDateValue = []
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-100, 'days') || current > moment().endOf('day').add('days')) ;
    },
    setOptionChart() {
      const data = this.chartData
      const xData = []
      const series = []
      if (data.length > 0) {
        data.forEach(item => {
          const date = item.date.split('-')
          xData.push(date[1] + '-' + date[2])
        })
        for (let o of this.ziduan) {
          let zd = this.ziduanOptions.find(e => e.label === o)
          let d = []
          for (let item of data) {
            d.push(item[zd.value])
          }
          series.push({
            name: zd.label,
            type: 'bar',
            barMinHeight: 5, // 设置最小高度
            data: d
          })
        }
      }
      let legend = {
        data: this.ziduan
      }
      setOption3(xData, series, legend)
    },
    initChart() {
      let time = 200
      this.timeout && clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        init('chart-account')
        this.setOptionChart()
      }, time);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
  },
  deactivated() {
    this.$EventBus.$off('onresize', this.initChart)
  },
  beforeDestroy() {
    this.$EventBus.$off('onresize', this.initChart)
  },
  components:{CustomTable},
}
</script>

<style lang="less" scoped>
.container{
  .search{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .time{
    display: flex;
    align-items: center;
    .yhs{
      width: 120px;
      margin-right: 20px;
    }
    .select{
      width: 180px;
      margin-right: 20px;
    }
    .select2{
      width: 200px;
      margin-right: 20px;
    }
    .salesExtra{
      display: flex;
      align-items: center;
      margin-right: 24px;
      a{
        margin-left: 24px;
        color: rgba(0, 0, 0, 0.88);
      }
      .currentDate{
        color: #1890ff;
      }
    }
  }
  .chart{
    margin-top: 20px;
  }
  .customTable{
    margin-top: 20px;
  }
}
</style>